from __future__ import division
import os
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import xml.dom.minidom
import numpy as np

ImgPath = '20230831_960_540_200/'
AnnoPath = '20230831_960_540_200_xml/'
ProcessedPath = '20230831_960_540_200_crop'
if not os.path.exists(ProcessedPath):
    os.mkdir(ProcessedPath)

filelist = os.listdir(ImgPath)

for file in filelist:
    if file.endswith('.jpg'):
        image_pre, ext = os.path.splitext(file)
        imgfile = ImgPath + file
        print(imgfile)
        if not os.path.exists(AnnoPath + image_pre + '.xml' ):
            continue
        xmlfile = AnnoPath + image_pre + '.xml'
        DomTree = xml.dom.minidom.parse(xmlfile)
        annotation = DomTree.documentElement
        filenamelist = annotation.getElementsByTagName('filename')
        filename = filenamelist[0].childNodes[0].data
        objectlist = annotation.getElementsByTagName('object')
        i = 1
        for objects in objectlist:
            namelist = objects.getElementsByTagName('name')
            objectname = namelist[0].childNodes[0].data
            savepath = objectname        
            if not os.path.exists(ProcessedPath + '/' + savepath):
                os.makedirs(ProcessedPath + '/' + savepath)
            bndbox = objects.getElementsByTagName('bndbox')
            cropboxes = []
            for box in bndbox:
                x1_list = box.getElementsByTagName('xmin')
                x1 = float(x1_list[0].childNodes[0].data)
                y1_list = box.getElementsByTagName('ymin')
                y1 = float(y1_list[0].childNodes[0].data)
                x2_list = box.getElementsByTagName('xmax')
                x2 = float(x2_list[0].childNodes[0].data)
                y2_list = box.getElementsByTagName('ymax')
                y2 = float(y2_list[0].childNodes[0].data)
                w = x2 - x1
                h = y2 - y1
                obj = np.array([x1,y1,x2,y2])
                shift = np.array([[1,1,1,1]])
                XYmatrix = np.tile(obj,(1,1))
                cropboxes = XYmatrix * shift
                img = Image.open(imgfile)
                for cropbox in cropboxes:
                    # 在这个位置添加以下代码，用于调试输出
                    print("Cropbox:", cropbox)

                    cropedimg = img.crop(cropbox)
                    if not cropedimg:
                        print("Warning: Empty cropedimg")
                    else:
                        cropedimg.save((ProcessedPath + '/' + savepath + '/' + image_pre + '_' + str(i) + '.jpg'), quality=95, subsampling=0)
                    i += 1